package com.gxedu.springenvironmentconfig.sourceloader;

import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
liu_gx
 * 基于spring cloud中提供的一个属性文件的扩展接口PropertySourceLocator扩展配置文件(spring boot启动的过程中会触发调用）
 **/
public class JsonProperySourceLocator implements PropertySourceLocator{

    private final static String DEFAULT_LOCATION="classpath:gx.json";

    private final ResourceLoader resourceLoader=new DefaultResourceLoader(getClass().getClassLoader());

    @Override
    public PropertySource<?> locate(Environment environment) {
        GxDefineJsonProperySource jsonProperySource=
                new GxDefineJsonProperySource("gxDefineJsonProperySource",mapPropertySource());
        return jsonProperySource;
    }

    private Map<String,Object> mapPropertySource(){
        //访问远程配置？http接口。
        // TODO 微服务配置中心实现形式即可在这里远程RPC加载配置到spring环境变量中
        // 读取classpath下的gx.json解析
        Resource resource=this.resourceLoader.getResource(DEFAULT_LOCATION);
        if(resource==null){
            return null;
        }
        Map<String,Object> result=new HashMap<>();
        JsonParser jsonParser= JsonParserFactory.getJsonParser();
        Map<String,Object> fileMap=jsonParser.parseMap(readFile(resource));
        processorMap("",result,fileMap);
        return result;
    }

    private void processorMap(String prefix,Map<String,Object> result,Map<String,Object> fileMap){
        if(prefix.length()>0){
            prefix+=".";
        }
        for (Map.Entry<String,Object> entrySet:fileMap.entrySet()){
            if(entrySet.getValue() instanceof Map){
                processorMap(prefix+entrySet.getKey(),result,(Map<String,Object>)entrySet.getValue());
            }else{
                result.put(prefix+entrySet.getKey(),entrySet.getValue());
            }
        }
    }

    /**
     * JSON格式
     * {
     *     {
     *         {
     *
     *         }
     *     }
     * }
     * @param resource
     * @return
     */
    private String readFile(Resource resource) {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(resource.getFile());
            String str = "";
            byte[] readByte = new byte[1024];
            int length;
            while ((length = fileInputStream.read(readByte)) > 0) {
                str += new String(readByte, 0, length, "UTF-8");
            }
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
